package fr.dauphine.spring.ctl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import fr.dauphine.spring.bo.Client;
import fr.dauphine.spring.dao.ClientDAO;

@Controller
@RequestMapping("clients.html")
public class ClientsController {

	@Autowired
	private ClientDAO clientDAO;

	@RequestMapping(method = RequestMethod.GET)
	public String affichage(ModelMap model) throws Exception {
		model.addAttribute("clients", clientDAO.get());
		model.addAttribute("utilisateur", SecurityContextHolder.getContext().getAuthentication()
				.getName());
		System.out.println("start liste clients");
		return "clients";
	}

	@RequestMapping(params = "validation=Ajouter", method = RequestMethod.POST)
	public String ajout() {
		return "redirect:client.html";
	}

	@RequestMapping(params = "validation=Supprimer", method = RequestMethod.POST)
	public String suppression(@RequestParam("idClient") String[] idClient) {
		try {
			if (idClient.length > 0) {
				for (int i = 0; i < idClient.length; i++) {
					Client client = clientDAO.get(idClient[i]);
					clientDAO.delete(client);
				}
			}

			return "redirect:clients.html";
		} catch (Exception ex) {
			ex.printStackTrace();
			return "erreur";
		}
	}

	@RequestMapping(params = "validation=search", method = RequestMethod.POST)
	public String recherche(ModelMap model, @RequestParam("search") String search) throws Exception {
		if (search != null && !search.trim().equals("")) {
			System.out.println("Recherche de clients");
			model.addAttribute("clients", clientDAO.getClientsLike(search));
			model.addAttribute("utilisateur", SecurityContextHolder.getContext()
					.getAuthentication().getName());
		} else {
			System.out.println("Recherche vide");
			model.addAttribute("clients", clientDAO.get());
			model.addAttribute("utilisateur", SecurityContextHolder.getContext()
					.getAuthentication().getName());
		}
		// model.addAttribute("search", attributeValue)
		return "clients";
	}
}
